package com.video.controller;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.crypto.SecureUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.video.common.dto.LoginDto;
import com.video.common.lang.Result;
import com.video.entity.User;
import com.video.service.UserService;
import com.video.util.JwtUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.sql.Timestamp;
import java.time.LocalDateTime;


/**
 * @author maomao
 */
@RestController
public class AccountController {

    @Resource
    private UserService userService;

    @Resource
    JwtUtils jwtUtils;

    @PostMapping("/login")
    public Result login(@Validated @RequestBody LoginDto loginDto, HttpServletResponse response) {

        User user = userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername()).eq("approve_state", 1));
        Assert.notNull(user, "用户名和密码不匹配");

        if (!user.getPassword().equals(SecureUtil.md5(loginDto.getPassword()))) {
            return Result.fail("用户名和密码不匹配");
        }

        String jwt = jwtUtils.generateToken(user.getId());

        response.setHeader("Authorization", jwt);

        response.setHeader("Access-Control-Expose-Headers", "Authorization");

        return Result.success(MapUtil.builder()
                .put("id", user.getId())
                .put("username", user.getUsername())
                .put("industry", user.getIndustry())
                .put("description", user.getDescription())
                .put("qq", user.getQq())
                .put("wechat", user.getWechat())
                .put("count", user.getVideoCount())
                .put("isAdmin", user.getIsAdmin())
                .map()
        );
    }

    @RequiresAuthentication
    @GetMapping("/logout")
    public Result logout() {
        SecurityUtils.getSubject().logout();
        return Result.success(null);
    }

    @PostMapping("/register")
    public Result register(@Validated @RequestBody LoginDto loginDto) {
        User user = userService.getOne(new QueryWrapper<User>().eq("username", loginDto.getUsername()));
        User admin = userService.getOne(new QueryWrapper<User>().eq("username", "admin"));

        if (user != null && user.getApproveState() == 0) {
            throw new IllegalArgumentException("账户审核中");
        } else if (user != null) {
            throw new IllegalArgumentException("账户已存在");
        }

        user = new User();
        user.setUsername(loginDto.getUsername());
        user.setPassword(SecureUtil.md5(loginDto.getPassword()));
        user.setCompanyName(loginDto.getCompanyName());
        user.setContactPerson(loginDto.getContactPerson());
        user.setPhoneNumber(loginDto.getPhoneNumber());
        user.setQq(loginDto.getQq());
        user.setWechat(loginDto.getWechat());
        user.setVideoCount(0);
        user.setCreated(Timestamp.valueOf(LocalDateTime.now()));
        user.setStatus(0);
        user.setIsAdmin(0);
        user.setApproveUser(admin.getId());
        user.setApproveState(0);
        userService.save(user);

        return Result.success(200, "注册成功", null);
    }
}
